import config from './../../config'
const API = config.api
const app = getApp()
import {
  phoneFun
} from '../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isMask:false,
    customerserviceshow:false,
    navigationSetting:{
      title:'填写资料',
      height: app.globalData.navBarHeight,
      paddingTop: app.globalData.statusBarHeight,
      backgroundColor:'#fff',
      size:'default'
    },
    index: 0,
    searchResult: [],
    searchResult3: ['请选择车型', '雅阁', '型格', '凌派', '缤智', '皓影', '奥德赛', 'ZR-V致在', '极湃', '飞度', '冠道'],
    isArea: false,
    isCar: false,
    codeLock: false,
    sendCodeTime: 0,
    ownerType: null,
    /* 车牌键盘数据 */
    keyValue: {
      keyValue1: '京津渝沪冀晋辽吉黑苏',
      keyValue2: '浙皖闽赣鲁豫鄂湘粤琼',
      keyValue3: '川贵云陕甘青蒙桂宁新',
      keyValue4: '藏使领警学港澳',
      keyNumber: '1234567890',
      keyLetterValue1: 'QWERTYUIOP',
      keyLetterValue2: 'ASDFGHJKL',
      keyLetterValue3: 'ZXCVBNM',
      showkKeyboardType: true, //1是省份键盘 0是数字字母键盘
      keyBg: '',
    },
    area: {},
    area2: '',
    inputPlate: {
      plates: app.globalData.ETCRegisterInfo.apply.apply_carlicence ? app.globalData.ETCRegisterInfo.apply.apply_carlicence.splice("") : [], //接收输入的内容
      plateCount: [1, 2, 3, 4, 5, 6, 7], //输入框的个数
    },
    isShowKeyboard: false, //是否显示键盘,默认显示
    searchTime: null,
    customer: ""
  },
  isObj(object) { // 判断是否是object
    return object && typeof (object) == 'object' && Object.prototype.toString.call(object).toLowerCase() == "[object object]";
  },
  isArray(object) { // 判断是否是array
    return Object.prototype.toString.call(object) === '[object Array]';
  },
  ChooseColor(e) {
    this.confirmPalet()
    let type = e.currentTarget.dataset.type;
    this.setData({
      cur: type
    })
  },
  cancelCode2() {
    this.setData({
      customerserviceshow: false,
      isMask: false,
    })
  },
  phoneOn() {
    wx.makePhoneCall({
      phoneNumber: '400-830-8999' //仅为示例，并非真实的电话号码
    })
  },
  phoneOn2() {
    wx.makePhoneCall({
      phoneNumber: '800-830-8999' //仅为示例，并非真实的电话号码
    })
  },
  confirmPalet(){
    this.setData({
      isMask:true,
      customerserviceshow:true
    })
  },
  //选择车牌修改确认
  // confirmPalet() {
  //   if (this.data.cur == 0 && this.data.licensePlate.length < 7) {
  //     wx.showToast({
  //       title: '请填写正确的车牌',
  //       icon: 'none',
  //       image: '',
  //       duration: 3000
  //     });
  //     return;
  //   }
  //   if (this.data.cur == 4 && this.data.licensePlate.length < 8) {
  //     wx.showToast({
  //       title: '请填写正确的车牌',
  //       icon: 'none',
  //       image: '',
  //       duration: 3000
  //     });
  //     return;
  //   }
  //   // if (this.data.area && !this.data.area.shopCode) {
  //   //     wx.showToast({
  //   //         title: '请选择门店',
  //   //         icon: 'none',
  //   //         image: '',
  //   //         duration: 3000
  //   //     });
  //   //     return;
  //   // }
  //   if (this.data.area2 == '' || this.data.area2 == '请选择车型') {
  //     wx.showToast({
  //       title: '请选择车型',
  //       icon: 'none',
  //       image: '',
  //       duration: 3000
  //     });
  //     return;
  //   }
  //   if (!phoneFun(this.data.phoneNumber)) {
  //     wx.showToast({
  //       title: '手机号有误',
  //       icon: 'none',
  //       duration: 3000
  //     });
  //     return
  //   }
  //   wx.showLoading({
  //     title: '正在提交资料',
  //     mask: true,
  //   });
  //   app.http(API.apiCheckVehicle, {
  //     qzFlag: 1,
  //     temporaryFlag: 0,
  //     vehicle_color: this.data.cur,
  //     vehicle_plate: this.data.licensePlate,
  //     zhtxMobile: this.data.phoneNumber,
  //   }).then(res => {
  //     wx.hideLoading()
  //     if (res.code == 200) {
  //       let rspData = JSON.parse(res.rspData)
  //       console.log(rspData)
  //       if (rspData.success) {
  //         if (this.isObj(rspData.object)) {
  //           if (rspData.object.return_code == '0000') {
  //             this.orderPayment()
  //           } else {
  //             wx.showModal({
  //               title: '提示',
  //               content: rspData.object.return_msg,
  //               confirmColor: '#005866',
  //               showCancel: false,
  //               success(res) {}
  //             })
  //           }
  //         } else {
  //           if (this.isArray(rspData.object)) {
  //             if (rspData.object[0].return_code == '0000') {
  //               this.orderPayment()
  //             } else {
  //               wx.showModal({
  //                 title: '提示',
  //                 content: rspData.object.return_msg,
  //                 confirmColor: '#005866',
  //                 showCancel: false,
  //                 success(res) {}
  //               })
  //             }
  //           } else {
  //             wx.showModal({
  //               title: '提示',
  //               content: rspData.object[0].return_msg,
  //               confirmColor: '#005866',
  //               showCancel: false,
  //               success(res) {}
  //             })
  //           }
  //         }
  //       } else {
  //         wx.showModal({
  //           title: '提示',
  //           content: rspData.msg,
  //           confirmColor: '#005866',
  //           showCancel: false,
  //           success(res) {}
  //         })
  //       }
  //     } else {
  //       wx.showModal({
  //         title: '提示',
  //         content: res.message,
  //         confirmColor: '#005866',
  //         showCancel: false,
  //         success(res) {}
  //       })
  //     }
  //   }).catch(err => {
  //     wx.showToast({
  //       title: err.message,
  //       icon: 'none',
  //       duration: 3000,
  //       mask: false
  //     });
  //   })
  // },
  // 选择车辆类型
  changeOwnerType(e) {
    this.confirmPalet()
    this.setData({
      ownerType: e.detail.value
    })
  },
  // 订单支付
  orderPayment() {

    if (this.data.cur == 0 && this.data.licensePlate.length < 7) {
      wx.showToast({
        title: '请填写正确的车牌',
        icon: 'none',
        image: '',
        duration: 3000
      });
      return;
    }
    if (this.data.cur == 4 && this.data.licensePlate.length < 8) {
      wx.showToast({
        title: '请填写正确的车牌',
        icon: 'none',
        image: '',
        duration: 3000
      });
      return;
    }
    if (!this.data.ownerType) {
      wx.showToast({
        title: '请选择车辆类型',
        icon: 'none',
        duration: 3000
      });
      return
    }
    if (!phoneFun(this.data.phoneNumber)) {
      wx.showToast({
        title: '手机号有误',
        icon: 'none',
        duration: 3000
      });
      return
    }
    let userId = wx.getStorageSync("userId");

    wx.showLoading({
      title: '正在提交资料',
      mask: true,
    });
    // console.log(this.data.area2);
    app.http(API.createOrder, {
      customer: this.data.customer,
      etcUserType: this.data.ownerType,
      payMode: 2,
      channel: 1,
      type: 6,
      // validCode: this.data.userinfo.code,
      phone: this.data.phoneNumber,
      vehColor: this.data.cur,
      vehPlate: this.data.licensePlate,
      shopCode: this.data.area.shopCode,
      shopName: this.data.area.name,
      carSize: this.data.area2,
      carBrand: 0,
      userId: userId
    }).then(res => {
      if (res.code == 200) {
        wx.hideLoading()
        wx.redirectTo({
          url: '/pages/addIDcard/addIDcard'
        })
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none',
          image: '',
          duration: 3000
        });
      }
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 3000,
        mask: false
      });
    })
  },

  // 发送验证码
  onSendVerificationCode() {
    if (this.data.codeLock) return
    if (!this.data.userId) {
      wx.showToast({
        title: '您还未登陆',
        icon: 'none',
        image: '',
        duration: 3000
      });
      return
    }

    if (!phoneFun(this.data.phoneNumber)) {
      wx.showToast({
        title: '手机号有误',
        icon: 'none',
        duration: 3000
      });
      return
    }

    this.setData({
      codeLock: true
    })
    app.http(API.sendCode, {
        phone: this.data.phoneNumber
      })
      .then(res => {
        console.log(res)
        if (res.code != '200') {
          wx.showToast({
            title: res.message || '发送失败',
            icon: 'none',
            duration: 3000,
            mask: false
          });

          setTimeout(() => {
            this.setData({
              codeLock: false
            })
          }, 2000)

          return
        }
        wx.showToast({
          title: '发送成功',
          icon: 'success',
          duration: 3000,
          mask: false
        });
        this.setData({
          sendCodeTime: 60
        })
        this.sendCodeTimer = setInterval(() => {
          this.setData({
            sendCodeTime: --this.data.sendCodeTime
          })
          if (this.data.sendCodeTime <= 0) {
            clearInterval(this.sendCodeTimer);
            this.setData({
              codeLock: false,
              sendCodeTime: 0,
            })
          }
        }, 1000)

      })
      .catch(err => {
        this.setData({
          codeLock: false
        })
        wx.showToast({
          title: '发送验证码失败',
          icon: 'none',
          image: '',
          duration: 3000,
          mask: false
        });
      })
  },
  search(value) {
    app.http(API.apiEtcShop, {
      carBrand: 0,
      name: value,
      pageSize: 100
    }).then(res => {
      if (res.code == 200) {
        let searchResult = res.data.list;
        searchResult.map(res => {
          let searchName = res.province + '-' + res.city + '-' + res.area + '-' + res.name;
          // value = value
          // let reg = new RegExp(value, 'g')
          // let searchNameList = searchName.replace(reg, ',' + value + ',').split(',').map(res => {
          //     let isSelect = false;
          //     if (res == value) {
          //         isSelect = true;
          //     }
          //     return {
          //         name: res,
          //         isSelect: isSelect
          //     }
          // })
          // res.searchNameList = searchNameList
          res.searchName = searchName
          return res
        })
        this.setData({
          searchResult: searchResult
        })
      }

    })
    clearInterval(this.data.searchTime);
  },
  selectArea() {
    this.confirmPalet()

    // this.setData({
    //   isArea: true
    // })
  },
  selectCar() {
    this.confirmPalet()
    // this.setData({
    //   isCar: true
    // })
  },
  cancelSearch() {
    clearInterval(this.data.searchTime);
    this.setData({
      isArea: false,
      searchTime: null,
      searchResult: [],
      searchName: null,
    })
  },


  cleanInput() {
    this.setData({
      searchTime: null,
      searchResult2: [],
      searchName: null
    })
  },

  defineSearch(e) {
    let area = e.currentTarget.dataset.item;
    this.setData({
      area
    })
    this.cancelSearch()
  },
  // 确认选择车型
  bindPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value,
    })
    this.setData({
      area2: this.data.searchResult3[this.data.index]
    })
    // console.log('picker发送选择改变，携带值为'+this.data.searchResult3[this.data.index])
    // console.log(this.data.area2);
  },
  onInputSearch(e) {
    clearInterval(this.data.searchTime);

    this.setData({
      searchResult: []
    })
    if (!e.detail.value) {
      return;
    };
    let value = e.detail.value.replace(/\s+/g, "")
    this.data.searchTime = setTimeout(() => {
      this.setData({
        searchValue: value
      })
      this.search(value)
    }, 1000)
  },

  // input 数据处理
  onInputData(e) {
    console.log(e.currentTarget.dataset.key)
    this.setData({
      [e.currentTarget.dataset.key]: e.detail.value.replace(/\s+/g, "")
    })
  },
  /* 车牌键盘输入组件 */
  //唤起键盘事件
  onFocusTap: function () {
    // this.data.isShowKeyboard = true;
    this.setData({
      isShowKeyboard: this.data.isShowKeyboard
    })
    this.confirmPalet()
  },
  //关闭键盘
  onCloseKeyboardTap: function () {
    this.data.isShowKeyboard = false;
    this.setData({
      isShowKeyboard: this.data.isShowKeyboard
    })
  },
  //点击键盘事件
  onKeyboardTap: function (event) {
    // console.log(event.currentTarget.dataset.value)
    var value = event.currentTarget.dataset.value;
    switch (value) {
      case 'ABC':
        this.data.keyValue.showkKeyboardType = !this.data.keyValue.showkKeyboardType;
        break;
      case 'delete':
        if (this.data.inputPlate.plates.length > 0) {
          this.data.inputPlate.plates.pop();
        }
        //如果输入的值被删除完，显示省份键盘
        if (this.data.inputPlate.plates.length == 0) {
          this.data.keyValue.showkKeyboardType = true;
        }
        // if (this.data.inputPlate.plates.length > 0) {
        //     this.data.keyValue.showkKeyboardType = false;
        // }
        break;
      default:
        if (this.data.inputPlate.plates.length == 8) {
          //替换数组最后一个元素
          this.data.inputPlate.plates.splice(7, 1, value);
        } else {
          this.data.inputPlate.plates.push(value);
        }
    }

    // console.log(this.data.inputPlate.plates);
    this.setData({
      keyBg: '#000'
    })
    // console.log(this.data.keyBg)
    // 切换英文键盘
    if (this.data.inputPlate.plates.length > 0) {
      this.data.keyValue.showkKeyboardType = false;
    }
    let num = this.data.cur;
    if (this.data.inputPlate.plates.length == 7) {
      num = 0;
    } else if (this.data.inputPlate.plates.length > 7) {
      num = 4
    }
    let licensePlate = '';
    this.data.inputPlate.plates.forEach(e => {
      licensePlate += e
    });
    this.setData({
      licensePlate: licensePlate,
      cur: num,
      keyValue: this.data.keyValue,
      inputPlate: this.data.inputPlate,
      isShowKeyboard: this.data.isShowKeyboard
    })
  },
  /* 车牌键盘输入组件 */
  showVehCertBack() {
    this.setData({
      isShowVehCertBack: true,
      showMask: true
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    this.setData({
      customer: options.customer
    })
    let userId = wx.getStorageSync('userId') || '';
    let phoneNumber = wx.getStorageSync('phoneNumber') || '';
    this.setData({
      userId,
      phoneNumber
    })
    app.getDeviceSize().then(res => {
      const {
        bottomLift,
        windowHeight,
        statusBarHeight
      } = res
      this.setData({
        bottomLift,
        windowHeight,
        statusBarHeight
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})